package com.wangjw.tuling.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * Created by wangjianwen on 2018/12/6.
 */
public class CuratorCrud {

    private static final String CONNECT_URL = "47.96.129.248:2181,116.62.115.21:2181,47.96.224.44:2181";

    private CuratorFramework curatorFramework;

    public CuratorCrud() {
        // 1 重试策略：初试时间为1s 重试10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);

        // 2 通过工厂创建连接
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_URL)
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();

        // 3 开启连接
        curatorFramework.start();
    }

    public String createPersistent(String path, String data) {
        try {
            curatorFramework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(path, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getData(String path) {
        try {
            return new String(curatorFramework.getData().forPath(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void delete(String path) {
        try {
            curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setData(String path, String data) {
        try {
            curatorFramework.setData().forPath(path, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String path = "/nijj/teacher";
        CuratorCrud curatorCrud = new CuratorCrud();
        curatorCrud.delete(path);
        curatorCrud.createPersistent(path, "chinese");
        System.out.println(curatorCrud.getData(path));
    }
}
